package com.example.demomongodb.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.example.demomongodb.entity.Student;
import com.example.demomongodb.form.StudentForm;
import com.example.demomongodb.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


/**
 * @version 1.0.0
 * @className: StudentServiceImpl
 * @description:
 * @author: zhangjunfa
 * @date: 2022/11/8 15:58
 */
@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Object addStudent(Student student) {
        student.set_id(IdUtil.simpleUUID());
        student.setCreateTime(DateTime.now());
        return mongoTemplate.save(student);
    }

    @Override
    public Object getStudent(StudentForm student) {
        Query query = new Query();
        if (!StringUtils.hasText(student.getId())) {
            query.addCriteria(Criteria.where("_id").is(student.getId()));
        }
        if (!StringUtils.hasText(student.getName())) {
            query.addCriteria(Criteria.where("name").is(student.getName()));
        }
        if (null != student.getAge()) {
            query.addCriteria(Criteria.where("age").is(student.getAge()));
        }
        if (null != student.getScore()) {
            query.addCriteria(Criteria.where("score").is(student.getScore()));
        }
        return mongoTemplate.find(query, Student.class);
    }
}
